﻿#include "server.h"
#include <QDebug>
#include <QtConcurrent/QtConcurrent>

Server::Server(QObject *parent) :
    QObject(parent),
    m_init(true),
    m_port(7555),
    m_exit(false)
{
    ushort SocketVersonRequested;
    WSADATA wsa;

    SocketVersonRequested = MAKEWORD(2,0);

    if(WSAStartup(SocketVersonRequested,&wsa) != 0)
    {
        qDebug()<<"WSAStartup fail";
        m_init = false;
    }

    if (LOBYTE(wsa.wVersion) != 2 || HIBYTE(wsa.wVersion) != 0)
    {
        WSACleanup();
        m_init = false;
    }

    m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(m_socket == INVALID_SOCKET)
    {
        qDebug()<<"socket fail";
        m_init = false;
    }
    start();
}

Server::~Server()
{
    m_exit = true;
    closesocket(m_connect);
    closesocket(m_socket);
    WSACleanup();
}

bool Server::start(int port)
{
    if(!m_init)
        return false;
    m_seradd.sin_family = AF_INET;
    m_seradd.sin_port = htons(m_port);
    m_seradd.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(m_socket,(sockaddr*)&m_seradd,sizeof(m_seradd)) != 0)
    {
        qDebug()<<"bind fail";
        return false;
    }
    if(listen(m_socket,1) != 0)
    {
        qDebug()<<"listen fail";
        return false;
    }
    QtConcurrent::run(QThreadPool::globalInstance(),this,&Server::acceptClient);
    return true;
}

int Server::writeData(const char *data,int len)
{
    if(m_connect != INVALID_SOCKET)
        return send(m_connect,data,len,0);
    return -1;
}

void Server::acceptClient()
{
    while(1)
    {
        if(m_exit)
            return;
        int clientlen = sizeof(m_cliadd);
        m_connect = accept(m_socket,(sockaddr*)&m_cliadd,&clientlen);
        emit signalConnect();
        while(1)
        {
            if(m_exit)
                return;
            char buf[1024];
            QThread::msleep(1);
            if(recv(m_connect,buf,1024,0) <= 0)
            {
                closesocket(m_connect);
                m_connect = INVALID_SOCKET;
                emit signalDisconnect();
                break;
            }
        }
    }

}
#include <QEvent>
